package com.ty.cloudpicture.api.imageSearch.sub;

import com.ty.cloudpicture.common.ErrorCode;
import com.ty.cloudpicture.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class GetImageFirstUrlApi {

    /**
     * 获取图片页面地址
     *
     * @param imageUrl
     * @return
     */
    public static String getImagePageFirstUrl(String imageUrl) {
        try {
            Document document = Jsoup.connect(imageUrl)
                    .timeout(5000)
                    .get();
            Elements scriptElements = document.getElementsByTag("script");
            for (Element scriptElement : scriptElements) {
                String scriptContent = scriptElement.html();
                if (scriptContent.contains("\"firstUrl\"")) {
                    Pattern pattern = Pattern.compile("\"firstUrl\"\\s*:\\s*\"(.*?)\"");
                    Matcher matcher = pattern.matcher(scriptContent);
                    if (matcher.find()) {
                        String firstUrl = matcher.group(1);
                        //处理转义字符
                        firstUrl = firstUrl.replaceAll("\\\\/", "/");
                        return firstUrl;
                    }
                }
            }
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"未找到url");
        } catch (IOException e) {
            log.error("搜索失败",e);
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 定义一个字符串变量url，存储百度图库的链接
        String url="https://graph.baidu.com/s?card_key=&entrance=GENERAL&extUiData[isLogoShow]=1&f=all&isLogoShow=1&session_id=3372582889025602557&sign=126a7e97cd54acd88139901740753048&tpl_from=pc";
        // 调用getImagePageFirstUrl方法，获取百度图库的第一页链接
        String result = getImagePageFirstUrl(url);
        // 打印结果
        System.out.println("result = " + result);
    }
}
